<template>
  <div class="test-detail-container">
    <div class="test-header">
      <div class="header-actions">
        <el-button type="primary" size="small" plain icon="el-icon-arrow-left" @click="goBack">返回</el-button>
      </div>
      <!-- 添加总成绩显示 -->
      <div class="test-score-summary" v-if="isGraded">
        <el-tag type="success" size="medium">总成绩: {{ totalScore }}/{{ totalPossibleScore }} 分</el-tag>
      </div>
    </div>

    <div class="questions-list" v-loading="loading">
      <div class="progress-bar-container">
        <div class="progress-stats">已完成: {{ completedQuestions }}/{{ questionDetails.length }}</div>
        <el-progress :percentage="progressPercentage" :stroke-width="18" :format="progressFormat"></el-progress>
      </div>
      
      <div v-for="(question, index) in questionDetails" :key="question.id" class="question-item">
        <div class="question-header">
          <h3 class="question-title">题目：<RichTextDisplay :content="question.questionText" /> ({{ question.type }})</h3>
        </div>
        
        <div class="question-content">
          <!-- 学生答案区域 -->
          <div class="student-answer-section">
            <h4 class="answer-title">学生答题：</h4>
            
            <!-- 如果已提交（isCommit为1），显示只读答案 -->
            <div v-if="question.isCommit === 1" class="student-answer-content">
              {{ answers[question.id] || '未作答' }}
            </div>
            
            <!-- 未提交且测试未截止，显示可编辑的答题框 -->
            <div v-else-if="!isTestDeadlineOver()">
              <el-input
                type="textarea"
                :rows="6"
                placeholder="请在此输入您的回答"
                v-model.trim="answers[question.id]"
                resize="none"
                class="answer-textarea">
              </el-input>
              <div class="answer-counter">
                <span>当前字数: {{ answers[question.id] ? answers[question.id].length : 0 }}</span>
              </div>
            </div>
            
            <!-- 测试已截止但未提交，显示只读答案 -->
            <div v-else class="student-answer-content">
              {{ answers[question.id] || '未作答' }}
            </div>
          </div>
          
                      <!-- 评分和评语区域（仅在已提交时显示） -->
            <div v-if="question.isCommit === 1" class="feedback-container">
              <!-- 显示评分（仅在已批改时显示） -->
              <div v-if="question.isCorrect === 1 && question.score !== null && question.score !== undefined" class="score-display">
                <h4 class="score-title">得分：</h4>
                <el-tag type="success" size="medium">
                  {{ question.score }}/{{ question.maxScore || 10 }} 分
                </el-tag>
              </div>
              
              <!-- 显示正确答案（仅在已提交且已批改时显示） -->
              <div v-if="question.isCorrect === 1 && (question.Answer || question.correctAnswer)" class="correct-answer-display">
                <h4 class="correct-answer-title">正确答案：</h4>
                <div class="correct-answer-content">
                  <RichTextDisplay :content="question.Answer || question.correctAnswer" />
                </div>
              </div>
              
              <!-- 显示评语（仅在已批改时显示） -->
              <div v-if="question.isCorrect === 1 && question.comment && question.comment.trim()" class="comment-display">
                <h4 class="comment-title">教师评语：</h4>
                <div class="comment-content">{{ question.comment }}</div>
              </div>
              
              <!-- 如果已提交但未批改 -->
              <div v-if="question.isCorrect !== 1" class="no-feedback">
                <el-tag type="info" size="small">等待教师评分</el-tag>
              </div>
            </div>
        </div>
      </div>
      
      <div class="form-actions">
        <el-button type="primary" @click="submitTest" :loading="submitting" :disabled="isTestSubmitted">提交答案</el-button>
        <el-button @click="saveAnswers" :disabled="isTestSubmitted">保存进度</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getTestDetail, submitTestAnswers, saveTestProgress } from '@/api/test'
import axios from 'axios'
import RichTextDisplay from '@/components/common/RichTextDisplay.vue'

export default {
  name: 'TestDetail',
  components: {
    RichTextDisplay
  },
  data() {
    return {
      testId: this.$route.params.id || '1',
      testPublishId: this.$route.query.testId, // 获取URL中的testId参数
      testlist: [],
      questions: [],
      answers: {},
      loading: false,
      submitting: false,
      submitted: false,
      lastSaved: null,
      questionDetails: [], // 修改为数组而非对象
      isGraded: false, // 新增属性
      totalScore: 0, // 新增属性
      totalPossibleScore: 0, // 新增属性
    }
  },
  computed: {
    completedQuestions() {
      return this.questionDetails.filter((q) => this.answers[q.id] && this.answers[q.id].trim() !== '').length
    },
    progressPercentage() {
      return (this.completedQuestions / this.questionDetails.length) * 100
    },
    // 检查题目是否有评分或评语
    hasFeedback() {
      return (question) => {
        return (question.score !== null && question.score !== undefined) || 
               (question.comment && question.comment.trim() !== '');
      }
    },
    // 检查测试是否已提交
    isTestSubmitted() {
      return this.questionDetails.some(question => question.isCommit === 1);
    }
  },
  created() {
    // 从sessionStorage获取测试数据
    this.loadTestDataFromSession();
    
    // 获取测试详情
    this.fetchTestDetail()

    // 检查测试是否已过期
    this.checkTestStatus();
  },
  methods: {
    progressFormat(percentage) {
      return `${percentage}%`
    },
    async fetchTestDetail() {
      this.loading = true
      try {
        // 获取测试基本信息
        const testInfoStr = sessionStorage.getItem('current_test_info');
        const testDetailsStr = sessionStorage.getItem('current_test_details');
        
        if (testInfoStr && testDetailsStr) {
          const testInfo = JSON.parse(testInfoStr);
          const testDetails = JSON.parse(testDetailsStr);
          
          //console.log("testInfo", testInfo);
          //console.log("testDetails", testDetails);
          this.testlist = testDetails;
          for (const detail of this.testlist) {
            if (detail.answer !== null) {
              this.answers[detail.questionId] = detail.answer;
            }
          }
          console.log('答案:', this.answers);
          
          // 从testlist中提取题目ID列表
          const questionIds = this.testlist.map(detail => detail.questionId);
          this.questions = []; // 清空问题列表
          
          // 为每个问题ID获取详细信息
          await this.fetchQuestionDetails(questionIds, this.testlist);
        } else {
          this.$message.error('无法获取测试信息，请从测试列表页进入');
          setTimeout(() => {
            this.$router.push({ name: 'MyAnswers' });
          }, 1500);
        }
      } catch (error) {
        console.error('获取测验详情错误', error);
        this.$message.error('获取测验详情失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    async fetchQuestionDetails(questionIds, testlist) {
      try {
        // 创建一个空的answers对象
        const newAnswers = {};
        
        // 清空问题详情数组，防止重复添加
        this.questionDetails = [];
        
        // 为每个问题ID发起请求获取详情
        for (const questionId of questionIds) {
          try {
            const response = await axios.get('/question/query', {
              params: { id: questionId }
            });
            
            if (response.data.code === 200) {
              const questionData = response.data.data;
              // 从testlist中找到对应的测试结果
              const resultDetail = testlist.find(detail => detail.questionId === questionId);
              
              // 创建问题对象
              const question = {
                id: questionData.id,
                questionText: questionData.questionText,
                imageUrl: questionData.imageUrl,
                type: questionData.type,
                score: resultDetail ? (resultDetail.score !== undefined ? resultDetail.score : null) : null,
                maxScore: questionData.score || 10, // 题目满分
                answerTime: questionData.answerTime,
                comment: resultDetail && resultDetail.comment !== undefined ? resultDetail.comment : '', // 确保comment字段不会为undefined
                // 标记是否已评分：有分数或评语都算已评分
                scored: resultDetail && (resultDetail.score !== null || (resultDetail.comment && resultDetail.comment.trim() !== '')),
                // 从resultDetail获取isCorrect字段
                isCorrect: resultDetail ? resultDetail.isCorrect : null,
                // 从resultDetail获取isSubmit字段，并映射为isCommit以保持前端一致性
                isCommit: resultDetail ? resultDetail.isSubmit : null,
                // 将后端返回的其他属性也保存下来
                ...questionData
              };
              
              console.log('问题详情加载完成:', {
                id: question.id,
                score: question.score,
                comment: question.comment,
                hasComment: !!question.comment,
                commentLength: question.comment ? question.comment.length : 0,
                scored: question.scored,
                isCorrect: question.isCorrect,
                isCommit: question.isCommit
              });
              
              // 只添加到questionDetails列表中，避免数据重复
              this.questionDetails.push(question);
              
              // 初始化该问题的答案
              newAnswers[questionId] = resultDetail && resultDetail.answer ? resultDetail.answer : '';
            }
          } catch (error) {
            console.error(`获取题目#${questionId}详情失败:`, error);
            // 如果获取失败，添加一个占位问题
            this.questionDetails.push({
              id: questionId,
              questionText: `题目#${questionId} (无法获取详情)`,
              score: 0,
              type: 'unknown'
            });
            newAnswers[questionId] = '';
          }
        }
        
        // 更新answers对象
        this.answers = newAnswers;
        
        // 计算总成绩
        this.totalScore = this.questionDetails.reduce((acc, question) => acc + (question.score || 0), 0);
        this.totalPossibleScore = this.questionDetails.reduce((acc, question) => acc + (question.maxScore || 10), 0);
        // 检查是否至少有一个题目已评分
        this.isGraded = this.questionDetails.some(question => question.scored);
        
        // console.log('成功获取题目详情:', this.questionDetails);
      } catch (error) {
        console.error('获取题目详情过程中出错:', error);
        this.$message.error('无法获取题目详情，请刷新页面重试');
      }
    },
    async submitTest() {
      // 检查是否过期
      if (this.isTestDeadlineOver()) {
        this.$message.error('测试已过期，无法提交');
        return;
      }
      
      if (!this.questionDetails.length) {
        this.$message.error('没有题目可以提交');
        return;
      }
      
      this.submitting = true;
      
      try {
        // 格式化提交数据 - 改为数组格式
        const submitData = [];
        
        console.log('测试数据:', this.testlist);
        // 转换为提交格式
        this.testlist.forEach(test => {
          submitData.push({
            id: test.id, // 使用id字段
            studentId: test.studentId,
            questionId: test.questionId,
            answer: this.answers[test.questionId]
          });
        });
        console.log('提交数据:', submitData);
        
        // 验证提交数据
        for (const item of submitData) {
          console.log('验证数据项:', {
            id: item.id,
            studentId: item.studentId,
            questionId: item.questionId,
            answer: item.answer
          });
          
          if (!item.id || item.id <= 0) {
            this.$message.error('数据错误：id无效');
            return;
          }
          if (!item.studentId) {
            this.$message.error('数据错误：studentId无效');
            return;
          }
          if (!item.questionId || item.questionId <= 0) {
            this.$message.error('数据错误：questionId无效');
            return;
          }
        }
        
        // 使用PUT方法调用API
        const response = await this.$http.put('/result/updateanswer', submitData)
        
        if (response.data.code === 200) {
          this.$message.success('测验提交成功！')
          this.submitted = true
          
          // 更新所有题目的isCommit状态为1
          this.questionDetails.forEach(question => {
            question.isCommit = 1;
          });
          
          // 清除会话存储中的测试数据
          sessionStorage.removeItem('current_test_info');
          sessionStorage.removeItem('current_test_details');
          sessionStorage.removeItem('current_test_id');
          
          // 设置标记，表示TestDetail页面已成功提交答案
          localStorage.setItem('test_just_submitted', 'true');
          
          // 将用户引导至答案列表页面 - 使用go(-1)而不是push
          setTimeout(() => {
            // 使用router.go(-1)返回上一页，这会触发实际的浏览器历史返回
            this.$router.go(-1);
            
            // 如果返回失败，则尝试使用push
            setTimeout(() => {
              if (document.location.href.includes('TestDetail')) {
                console.log('返回失败，尝试使用push');
                this.$router.push({ name: 'MyAnswers' });
              }
            }, 500);
          }, 1500)
        } else {
          this.$message.error(response.data.message || '提交失败，请稍后再试')
        }
      } catch (error) {
        console.error('提交测验答案出错:', error)
        
        // 显示更详细的错误信息
        if (error.response) {
          console.error('错误响应:', error.response.data)
          this.$message.error(`提交失败: ${error.response.data.message || '服务器错误'}`)
        } else if (error.request) {
          console.error('请求错误:', error.request)
          this.$message.error('提交失败：网络连接错误')
        } else {
          console.error('其他错误:', error.message)
          this.$message.error(`提交失败: ${error.message}`)
        }
      } finally {
        this.submitting = false
      }
    },
    async saveAnswers() {
      try {
        const answersData = { ...this.answers };
        // 保存到sessionStorage
        sessionStorage.setItem(`current_test_answers`, JSON.stringify(answersData));
        
        this.$message.success('已保存您的答题进度');
      } catch (error) {
        console.error('保存进度出错:', error);
        this.$message.error('保存进度失败，请稍后再试');
      }
    },
    
    // 从会话存储中加载测试数据
    loadTestDataFromSession() {
      const testId = sessionStorage.getItem('current_test_id');
      if (testId) {
        console.log('从会话加载测试数据，ID:', testId);
        this.testPublishId = testId;
        
        // 也尝试加载保存的答案
        const savedAnswers = sessionStorage.getItem('current_test_answers');
        if (savedAnswers) {
          try {
            this.answers = JSON.parse(savedAnswers);
            console.log('已恢复保存的答案');
          } catch (e) {
            console.error('加载保存的答案失败', e);
          }
        }
      } else {
        console.log('未找到测试ID在会话中，使用路由参数:', this.testPublishId);
      }
    },
    goBack() {
      // 使用router.go(-1)，这会触发实际的浏览器历史返回
      // 这比使用router.push更像真实的"返回"行为
      this.$router.go(-1);
      
      // 如果出于某种原因返回失败，再尝试使用push
      // setTimeout(() => {
      //   this.$router.push({
      //     name: 'MyAnswers'
      //   });
      // }, 100);
    },
    checkTestStatus() {
      console.log('测试对象:', this.testlist);
      console.log('测试是否过期:', this.isTestDeadlineOver());
      if (this.isTestDeadlineOver()) {
        this.$message.error('测试已过期，无法提交');
        return;
      }
    },

    isTestDeadlineOver() {
      if (!this.testlist || this.testlist.length === 0) {
        return false;
      }
      //console.log('测试结束时间:', test.endTime);
      return new Date() > new Date(this.testlist[0].endTime); 
    },
  }
}
</script>

<style scoped>
.test-detail-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.student-answer-content {
  margin: 10px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.feedback-container {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
  border-left: 4px solid #67c23a;
}

.score-display {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-display {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #dcdfe6;
}

.no-feedback {
  margin-top: 15px;
  color: #909399;
  font-style: italic;
}

.test-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
}

.questions-list {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.question-item:last-child {
  border-bottom: none;
}

.question-header {
  margin-bottom: 15px;
}

.question-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.student-answer-section h4 {
  font-size: 14px;
  color: #606266;
  margin-top: 0;
  margin-bottom: 10px;
}

.answer-textarea >>> .el-textarea__inner {
  font-size: 16px !important;
  font-weight: 700 !important;
  color: #000 !important;
  line-height: 1.6 !important;
}

.answer-counter {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.form-actions {
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  margin: 0 10px;
}

.progress-bar-container {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.progress-stats {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.answer-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.teacher-feedback {
  margin-top: 20px;
}

.score-display {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.score-title {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.comment-display {
  margin-bottom: 10px;
}

.comment-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.comment-content {
  font-size: 14px;
  color: #909399;
}

.correct-answer-display {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #dcdfe6;
}

.correct-answer-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.correct-answer-content {
  font-size: 14px;
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 8px;
  border-radius: 3px;
  border-left: 3px solid #67c23a;
}
</style>
